package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.util.HttpClientUtils;
import com.itheima.util.JwtUtils;
import com.itheima.util.WeiXinConstantPropertiesUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;


@Controller        //微信返回时是返回到回调页面
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Reference
    private MemberService memberService;


    @GetMapping("/login")
    public String genQrConnect(HttpSession session){
//微信开放平台的授权地址,%s 相当于占位符
        /*appid=唯一标识,申请的时候有
          redirect_uri 请使用urlEncode对链接进行处理
          "&response_type=code"
              scope:作用域:目前只支持snsapi_login
              state:用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
        * */
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUrl=WeiXinConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        System.out.println(redirectUrl);
        //微信要求要用urlEncoder转码
        try {
            redirectUrl= URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //设置值
        String url=String.format(
                baseUrl,
                WeiXinConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu"
        );
        System.out.println("二维码"+url);
        //重定向到请求微信的地址中
        return "redirect:"+url;
    }

//2.获取扫描人的信息,添加数据
@RequestMapping("/callback")
    public String callback(String code,String state){
    System.out.println("临时票据code"+code);
    System.out.println("状态码state"+state);
    try{
        //1.获取code值,临时票据,类似于验证码
        //2.有了验证码就可以请求微信的一个固定给地址
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        //凭借三个参数 :唯一标识; 密钥; 第一次访问微信公共返回的code
      String  accessTokenUrl=String.format(
                baseAccessTokenUrl,
                WeiXinConstantPropertiesUtil.WX_OPEN_APP_ID,
                WeiXinConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code
        );
        System.out.println("访问需要得到令牌和微信唯一标识的网址"+accessTokenUrl);
        //请求这个地址,会得到返回觉果(其中最中药的是token 和 openid)
        //使用httpclient发送请求,得到返回结果
        String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        //accessTokenInfo中封装的就是请求返回值(里面包含token和唯一标识)
        //转化为map集合
        Map mapAccessToken = (Map) JSON.parse(accessTokenInfo);
        String access_token = (String)mapAccessToken.get("access_token");
        String openid = (String)mapAccessToken.get("openid");
        System.out.println("access_token  "+access_token);
        System.out.println("openid  "+openid);
        //判断这个用户是否已经登录了(以唯一标识openid作为判断)
       Member member= memberService.findMemberByidCard(openid);
        if (member==null) {
            //没有此用户信息,表明此微信用户是第一次来,将他注册,保存到数据库
            //访问微信的资源服务器,获取到用户的信息
            String baseUserInfoUrl="https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            //拼接两个参数
            String userInfoUrl=String.format(
                    baseUserInfoUrl,
                    access_token,
                    openid
            );
            System.out.println("访问微信得到扫描人信息的网址"+userInfoUrl);
            //发送请求
            String userInfo = HttpClientUtils.get(userInfoUrl);
            //获取返回userInfo 字符串 扫描人的信息
            Map userInfoMap = (Map) JSON.parse(userInfo);
            String nickname = (String)userInfoMap.get("nickname");//昵称
            String headimgurl = (String)userInfoMap.get("headimgurl");//头像
            System.out.println("nickname 昵称"+nickname);
            System.out.println("headimgurl 头像地址"+headimgurl);
            member = new Member();
            member.setIdCard(openid);
            member.setName(nickname);
            member.setRemark(headimgurl);
            memberService.add(member);
        }
        //使用jwt将登录对象变成token字符传,然后地址带上字符串
        String jwtToken = JwtUtils.getJwtToken(member.getIdCard(), member.getName());
        //登录成功后返回首页,带上token
        return "redirect:http://localhost:80/pages/index.html?token="+jwtToken;
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }

}
}
